package com.hdyg.sixg.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.widget.ImageView;
import android.widget.Toast;

import com.hdyg.sixg.R;
import com.hdyg.sixg.activity.common.AppManager;
import com.hdyg.sixg.activity.common.BaseActivity;
import com.hdyg.sixg.app.MvpApplication;
import com.hdyg.sixg.entry.CountryBean;
import com.hdyg.sixg.mvp.Contrant.CWelcome;
import com.hdyg.sixg.mvp.base.BasePresenter;
import com.hdyg.sixg.mvp.base.BaseUrl;
import com.hdyg.sixg.mvp.base.GetParamUtil;
import com.hdyg.sixg.mvp.base.SpMsg;
import com.hdyg.sixg.mvp.presenter.PWelcome;
import com.hdyg.sixg.util.AlertDialogUtil;
import com.hdyg.sixg.util.ImageLoadUtil;
import com.hdyg.sixg.util.SPUtils;

import java.util.List;

import butterknife.BindView;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 欢迎页
 *
 * @author CZB
 * @time 2018/2/27 10:20
 */
public class WelcomeAty extends BaseActivity
        implements EasyPermissions.PermissionCallbacks,CWelcome.IVWelcome {

    @BindView(R.id.iv_image)
    ImageView ivImage;

    private long mExitTime;
    private CWelcome.IPWelcome mPresenter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.AppTheme);
        super.onCreate(savedInstanceState);
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_welcome;
    }

    @Override
    protected void initView() {
        ImageLoadUtil.loadGif(mContext, R.mipmap.gif_loadding, ivImage);
        requireSomePermission();
    }

    @Override
    protected void initData() {
        mPresenter.pGetAreaCode(BaseUrl.AREA_CODE_URL,GetParamUtil.getAreaCodeParam(""));
    }

    @Override
    protected void createPresenter() {
        mPresenter = new PWelcome(this);
    }

    /**
     * 有权限时执行下一步
     */
    private void nextDoing() {

        new Handler().postDelayed(() -> {
            String token = SPUtils.get(SpMsg.TOKEN,"");
            if (TextUtils.isEmpty(token)){
                startActivity(LoginActivity.class);
            }else {
                startActivity(MainActivity.class);
            }
            WelcomeAty.this.finish();
        }, 3000);
    }

    // 双击退出app
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                toastNotifyShort(R.string.sys_out_login);
                mExitTime = System.currentTimeMillis();
            } else {
                AppManager.getAppManager().AppExit(mContext);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    /**************************权限适配****************************/
    private static final int num = 123; // 用于验证获取的权

    /**
     * 动态申请权限
     */
    @AfterPermissionGranted(num)
    private void requireSomePermission() {
        String[] perms = {
                Manifest.permission.WRITE_EXTERNAL_STORAGE,//读写权限
                Manifest.permission.CAMERA//相机权限
        };

        if (EasyPermissions.hasPermissions(mContext, perms)) {
            // 已有权限，进行下一步
            nextDoing();
        } else {
            // Do not have permissions, request them now （没有权限，申请权限）
            EasyPermissions.requestPermissions((Activity) mContext, getResources().getString(R.string.sys_write_permission), num, perms);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        Toast.makeText(mContext.getApplicationContext(), R.string.sys_permission_success, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        Toast.makeText(mContext.getApplicationContext(), R.string.sys_permission_fail, Toast.LENGTH_SHORT).show();
        AlertDialogUtil.getInstance().showDialog(mContext, R.string.sys_toast, R.string.sys_permission_open,
                new AlertDialogUtil.OnClickYesListener() {
                    @Override
                    public void onClickYes() {
                        Intent intent = new Intent();
                        intent.setAction("android.intent.action.MAIN");
                        intent.setClassName("com.android.settings", "com.android.settings.ManageApplications");
                        startActivity(intent);
                        AppManager.getAppManager().AppExit(mContext);
                    }
                }, new AlertDialogUtil.OnClickNoListener() {
                    @Override
                    public void onClickNo() {
                        AppManager.getAppManager().AppExit(mContext);
                    }
                }, false);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 注意：this
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void vGetAreaCodeSuccess(List<CountryBean> dataBeans) {
        MvpApplication.countryBeanList = dataBeans;
    }
}
